<template>
  <CompOperate
    :field="field"
    :designer="designer"
    :design-state="designState"
    :parent-list="parentList"
    :parent-widget="parentWidget"
    :sub-form-row-id="subFormRowId"
    :sub-form-row-index="subFormRowIndex"
    :sub-form-col-index="subFormColIndex"
    :index-of-parent-list="indexOfParentList"
    :display-style="field.options.displayStyle"
  >
    <div>
      <div v-if="showComp(2)">
        <ReportSivlerMedical
          @jumpIndex="jumpIndex"
          :field="field"
          :datePlus="date"
          :timePlus="time"
        ></ReportSivlerMedical>
      </div>
      <div
        class="scene-report-auto-info-widget"
        :style="getStyle('head')"
        v-else
      >
        <template v-if="true">
          <div v-if="showComp(0)" class="report-home">
            <SceneReportHeadSivler
              :field="optionsInfo.reportHeaderConfig"
              :datePlus="date"
              :timePlus="time"
            ></SceneReportHeadSivler>
            <ReportAuto
              :field="field"
              @handleSubmit="handleSubmit"
              @handleHiddenSubmit="handleHiddenSubmit"
              ref="reportAutoRef"
              @handleBack="handleBack"
            />
            <SceneTipsSivler :field="optionsInfo.tipsConfig"></SceneTipsSivler>
          </div>
          <div v-if="showComp(1)" class="report-result">
            <SceneReportHeadSivler
              :field="optionsInfo.reportHeaderConfig"
              :datePlus="date"
              :timePlus="time"
            ></SceneReportHeadSivler>
            <div class="ReportResultBox">
              <ReportResult
              :state="1"
              :field="field"
              :devType="devType"
              @handleReport="handleReport"
              @handleReportAll="handleReportAll"
              @handleSignPrint="handleSignPrint"
            />
            </div>
            

            <!--底部操作按钮-->
            <div class="operate-info" v-if="true">
              <div class="back-home" @click="handleBack">
                <Icon name="wap-home" />
                <span class="back-text">
                  返回首页({{ backcountdown / 1000 }}s)
                </span>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
  </CompOperate>
</template>

<script>
import { Icon } from "vant";
import { pxToVw } from "@/utils/common";
import emitter from "@/utils/designer/emitter";
import { buildParentApi } from "@/utils/designer/util";
import ReportAuto from "./reportComps/reportAuto-sivler.vue";
import ReportResult from "./reportComps/reportResult.vue";
import ReportSivlerMedical from "./reportComps/report-sivler-medical.vue";
import SceneReportHeadSivler from "./reportComps/scene-report-head-sivler.vue";
import SceneTipsSivler from "./reportComps/scene-tips-sivler.vue";

import CompOperate from "@c/public/form-designer/devType/modules/compOperate.vue";
import mixin from "@sc/templateDetails/modules/homeMiddle/fieldMixin";
import { setReportStepInfo } from "@/store/modules/actions";
import * as types from "@c/public/form-designer/devType/datas-types";
import ReportKeyboard from "@sc/templateDetails/modules/homeMiddle/scene-widget/module/report/reportComps/reportKeyboard.vue";
import dayjs from "dayjs";
export default {
  name: "scene-report-sivler-medical-widget",

  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件

  mixins: [emitter, mixin],

  components: {
    ReportKeyboard,
    Icon,
    CompOperate,
    ReportResult,
    ReportAuto,
    ReportSivlerMedical,
    SceneReportHeadSivler,
    SceneTipsSivler,
  },

  props: {
    widget: Object,
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
    designState: {
      type: Boolean,
      default: false,
    },
    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },
    headTitle: {
      type: String,
      default: "",
    },
    visibleTitle: {
      type: Boolean,
    },
    //prop传入的表单JSON配置
    parentApi: {
      type: Object,
      default: () => buildParentApi(),
    },
    devType: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      step: this.field.options.reportInfoConfig.step,
      tipsShow: true,
      backcountdown: 120000,
      optionsInfo: Object(),
      date: dayjs().format("YYYY年MM月DD日"),
      time: dayjs().format("HH:mm"),
      week: "",
    };
  },

  computed: {
    // 设置的行内样式
    getStyle() {
      return function (val) {
        const self = this;
        let info = self.field?.options?.reportInfoConfig || Object();
        let Obj = Object();
        switch (val) {
          case "head":
            Reflect.set(Obj, "backgroundColor", `${info.backgroundColor}`);
            let step = info.step;
            switch (step) {
              case 0:
                Reflect.set(Obj, "height", pxToVw(info.headHeight));
                break;
              case 1:
                // let heighe = parseInt(info.headHeight) + 100;
                let heighe = parseInt(info.headHeight);
                Reflect.set(Obj, "height", pxToVw(heighe));
                break;
              case 2:
                break;
              default:
                Reflect.set(Obj, "height", pxToVw(info.headHeight));
                break;
            }
            return Obj;
          case "picture":
            Reflect.set(Obj, "height", pxToVw(info.imageHeight));
            Reflect.set(Obj, "width", pxToVw(info.imageWidth));
            Reflect.set(Obj, "borderRadius", pxToVw(info.imageRadius));
            return Obj;
        }
      };
    },

    //步距展示对应的组件
    showComp() {
      return function (val) {
        return this.optionsInfo.step === val;
      };
    },

    // 获取父级传递过来的step
    // getBackcountdown() {
    //   let { backcountdown } = this.field.options.reportInfoConfig;
    //   return backcountdown * 1000 || 120000;
    // },
  },

  created() {
    this.registerToRefList();
    this.initEventHandler();
    this.handleOnCreated();
  },

  mounted() {
    this.handleOnMounted();
    this.$store.dispatch("setReportStepInfo", 2);
    this.$store.dispatch("setSceneReportHead", false);
    this.updateTime();
    this.parentApi.executeParentMethod("cancelReadCardScan");
  },

  methods: {
    // 获取时间
    updateTime(val) {
      let timeType = this.field.options.reportInfoConfig.timeValue;
      if (!!val) {
        let msg = JSON.parse(val);
        if (!!msg && !!msg.timestamp) {
          let timestamp = dayjs.unix(msg.timestamp);
          [this.week, this.date, this.time] = dayjs(timestamp)
            .format(`d,${timeType},HH:mm`)
            .split(",");
        } else {
          [this.week, this.date, this.time] = dayjs()
            .format(`d,${timeType},HH:mm`)
            .split(",");
        }
      } else {
        [this.week, this.date, this.time] = dayjs()
          .format(`d,${timeType},HH:mm`)
          .split(",");
      }
    },
    jumpIndex() {
      this.optionsInfo.step = 0;
    },
    // 提交号别
    handleSubmit(params) {
      console.log("确定");
      this.parentApi.executeParentMethod("handleReport", params);
    },
    // c++ 提交号别
    handleHiddenSubmit(params) {
      this.parentApi.executeParentMethod("handleHiddenSubmit", params);
    },
    // 单独报到
    handleReport(params) {
      console.log("单独报到");
      this.parentApi.executeParentMethod("toReport", params);
    },

    // 批量报到
    handleReportAll(params) {
      console.log("批量报到");
      this.parentApi.executeParentMethod("reportAll", params);
    },

    handleSignPrint(params) {
      console.log("auto-打印小票");
      this.parentApi.executeParentMethod("signPrint", params);
    },
    // 倒计时
    countDown() {
      let { backCountdown } = this.optionsInfo;
      this.backcountdown = backCountdown * 1000 || 120000;
      if (this.timer) {
        clearInterval(this.timer);
      }
      this.timer = setInterval(() => {
        this.backcountdown = this.backcountdown - 1000;
        // 到达时间--返回首页-清空定时器
        if (this.backcountdown <= 0) {
          this.handleBack();
          clearInterval(this.timer);
        }
      }, 1000);
    },
    // 接收父组件传递过来的数据
    executeMethod(key, resp) {
      switch (key) {
        case "reportPatientInfo":
          let { code, data } = resp;
          if (code === 200) {
            this.optionsInfo.step = 1;
            this.$store.dispatch(
              "setReportPatientInfo",
              this.$lodash.cloneDeep(data)
            );
            this.countDown()
          }
          break;
        case "reportBack":
          Reflect.set(this.optionsInfo, "step", 0);
          break;
        case "timeDate":
          this.updateTime(resp);
          break;
      }
    },

    handleBack2() {
      this.executeMethod("reportBack");
    },

    // 返回首页
    handleBack() {
      this.optionsInfo.step = 2;
      // this.parentApi.executeParentMethod("openReadCardScan");
      this.parentApi.executeParentMethod("cancelReadCardScan");
    },
  },

  watch: {
    // 步距
    "optionsInfo.step": {
      handler: function (val) {
        if (val == undefined || val == 2 || val == 1) {
          this.parentApi.executeParentMethod("cancelReadCardScan");
        } else {
          this.parentApi.executeParentMethod("openReadCardScan");
        }
        const self = this;
        this.optionsInfo.step = parseInt(val);
        // 步骤过程发生变化--执行时间的倒计时
        if (parseInt(val) === 1) {
          // self.timer = setInterval(() => {
          //   self.backcountdown = self.backcountdown - 1000;
          //   // 到达时间--返回首页-清空定时器
          //   if (self.backcountdown <= 0) {
          //     self.handleBack();
          //     clearInterval(self.timer);
          //   }
          // }, 1000);
        } else {
          clearInterval(self.timer);
        }
      },
      deep: true,
      immediate: true,
    },

    // 监听父级传递过来的props--field
    field: {
      handler: function (val) {
        let key = val.options["config"];
        if (Reflect.has(val.options[key], "patientShowFields")) {
          Reflect.set(
            val.options[key],
            "patientShowFields",
            types["patientFields"]
          );
        }
        this.optionsInfo = val.options[key];
        // this.backcountdown = this.optionsInfo.backCountdown * 1000 || 120000;
        this.$store.dispatch("setReportStepInfo", this.optionsInfo.step);
        if (this.optionsInfo.step == 2) {
          this.$store.dispatch("setSceneReportHead", false);
        } else {
          this.$store.dispatch("setSceneReportHead", true);
        }
      },
      deep: true,
      immediate: true,
    },
  },

  destroyed() {
    this.unregisterFromRefList();
    this.$store.dispatch("setReportStepInfo", 0);
    this.$store.dispatch("setSceneReportHead", true);
  },
};
</script>

<style lang="scss" scoped>
.scene-report-auto-info-widget {
  font-size: 60px;
  overflow: hidden;
  background: transparent !important;
  position: relative;
   -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  .ReportResultBox{
    height: calc(100% - 460px);
  }
  //报到首页
  .report-home {
    height: 100%;
    background: transparent !important;
    // margin: 0 30px;
    display: flex;
    flex-direction: column;
  }

  //报到结果
  .report-result {
    height: 100%;
    width: 100%;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 0;
      height: 0;
      position: relative;
      z-index: 99999999999;
    }

    .operate-info {
      position: absolute;
      left: 50%;
      bottom: 0;
      transform: translate(-50%, 0);

      .back-home {
        align-self: center;
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 24px 52px;
        font-size: 44px;
        border-radius: 24px 24px 0 0;

        .van-icon {
          font-size: 58px;
          padding-right: 20px;
        }
      }
    }
  }
}
</style>